const mysql = require('mysql')
const config = require('../config')

const poolConnect = mysql.createPool(config.dbconfig)

const connect = {
  pool: poolConnect,
  query (sql) {
    if (config.env !== 'PROD') console.log('[SQL]:', sql)

    poolConnect.query.apply(poolConnect, arguments)
  },
  exec (sql, params = []) {
    return new Promise((resolve, reject) => {
      poolConnect.query(sql, params, (err, res) => {
        if (config.env !== 'PROD') console.log('[SQL]:', sql)

        if (err) return reject(err)
        else return resolve(res)
      })
    })
  }
}

connect.exec('select 1 + 1 as v').then(res => {
  console.log('MySQL connect successfull.')
}).catch(err => {
  console.error('MySQL connect fail.\n', err)
})

module.exports = connect
